#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Omar Vega Ramos
# E-mail: ovruni@riseup.net
# License: GNU GPL - GNU General Public License v3.0 or later
# http://www.gnu.org/licenses/gpl.html

from lxml import etree
import argparse, string, sys
import os.path

def osm_file(filename):
    if not filename.endswith('.osm'):
        raise argparse.ArgumentTypeError('argument input must be of type *.osm')
    return filename

parser = argparse.ArgumentParser(description='Format the text strings in the OSM files.')
parser.add_argument('input', type=osm_file, help='name of the input file')
parser.add_argument('-o', '--output', default='output.osm', help='name of the output file')
args = parser.parse_args()

if os.path.isfile(args.input) == False:
    sys.exit(sys.argv[0] + ": error: the file '" + args.input + "' does not exist")

tree = etree.parse(args.input)
names = tree.findall(".//tag[@k='name']")
modify = False

for name in names:
  new_name = name.get("v").title()
  new_name = new_name[:1] + new_name[1:].replace("De ", "de ").replace("La ", "la ").replace("El ", "el ").replace("Las ", "las ").replace("Los ", "los ").replace("Del ", "del ").replace(" Y ", " y ").replace(" E ", " e ").replace("&", "&amp;")

  if name.get("v") != new_name :
    name.set("v", new_name)
    modify = True

  parent = name.getparent()

  if name.get("v") == 'S/N' :
    parent.remove(name)
    modify = True

  if modify == True :
    parent.attrib['action'] = 'modify'
    modify = False

new_file = open(args.output, 'w')
new_file.write("<?xml version='1.0' encoding='UTF-8'?>\n")
new_file.write(etree.tostring(tree, encoding='unicode').replace("'", "&apos;").replace('"',"'"))
new_file.close()
sys.exit("Generated '" + args.output + "' file.")
